package net.wanho.zaixian.course.controller;

import com.alibaba.fastjson.JSONObject;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

@Controller
public class FileController {

    final String FILE_DEST_DIR = "D:/";
    @RequestMapping(value = "/filesystem/upload", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject upload(String CourseId, MultipartFile file) {
        JSONObject jsonObject = new JSONObject();
        try {
            String fileName = file.getOriginalFilename();
            String ext = fileName.substring(fileName.lastIndexOf("."));
            String filePath = FILE_DEST_DIR + UUID.randomUUID().toString()+ext;
            file.transferTo(new File(filePath));


            //1、加载配置文件
            ClientGlobal.init("fdfs_client.conf");
            //2、创建一个TrackerClient对象。
            TrackerClient trackerClient = new TrackerClient();
            //3、使用TrackerClient对象获得trackerserver对象。
            TrackerServer trackerServer = trackerClient.getConnection();
            //4、创建一个StorageClient对象。trackerserver、StorageServer两个参数。
            StorageClient storageClient = new StorageClient(trackerServer, null);
            //5、使用StorageClient对象上传文件。
            String[] strings = storageClient.upload_file(filePath, "png", null);
            //返回的数组包含两个元素分别类似于：group1、M00/00/00/wKhkwFyuYo6Aawy0AAH4I7umxyo333.png
            //返回的数组包含两个元素分别类似于：group1、M00/00/00/wKhkwFyuYo6Aawy0AAH4I7umxyo333.png
            new File(filePath).delete();
                jsonObject.put("success","true");
                jsonObject.put("fileId",strings[0]+"/"+strings[1]);
        }
            catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("success","false");
        }
        return jsonObject;
    }
}